<?php
namespace App;

// composer's auto loader
require __DIR__ . '/vendor/autoload.php';

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Url;
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Config\Adapter\Ini as ConfigIni;

try {

    // load configurations
    $config = new ConfigIni('app/config/config.ini');

    // Register an auto loader
    $loader = new Loader();
    $loader->registerDirs(array(
        $config->application->adaptersDir,
        $config->application->controllersDir,
        $config->application->formsDir,
        $config->application->modelsDir,
        $config->application->validatorsDir
    ))->registerNamespaces(
        array(
            'App' => 'app',
            'App\Forms' => 'app\forms'
        )
    )->register();

    // Create a DI
    $di = new FactoryDefault();

    // Setup the view component
    $di->set('view', function() {
        $view = new View();
        $view->setViewsDir('app/views/');
//        // wait for bug fix: https://github.com/phalcon/incubator/issues/536
//        $view->registerEngines(
//            array(
//                ".tpl" => 'Phalcon\Mvc\View\Engine\Smarty'
//            )
//        );

        return $view;
    });

    $di->set('url', function(){
        $url = new Url();
        $url->setBaseUri('/');

        return $url;
    });

    // DI smarty as service
    $di->set('smarty', function () use ($config) {
        $smarty = new \Smarty();
        $smarty->setTemplateDir($config->smarty->templateDir);

        return $smarty;
    });

    // Database connection
    $di->set('db', function () use ($config) {
        return new DbAdapter(
            array(
                "host"     => $config->database->host,
                "username" => $config->database->username,
                "password" => $config->database->password,
                "dbname"   => $config->database->name
            )
        );
    });

    // Handle the request
    $application = new Application($di);

    echo $application->handle()->getContent();

} catch (\Exception $e) {
    echo "PhalconException: ", $e->getMessage();
}